import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import router from '@/router'
import { getTimeStamp } from './auth'

// 定义超时时间
const timeOut = 30 * 60 * 1000

const instance = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // 设置axios请求的基础的基础地址
  timeout: 5000 // 定义5秒超时
})

// 请求拦截
instance.interceptors.request.use(
  config => {
    if (store.getters.token) {
      const isTimeOut = Date.now() - getTimeStamp() > timeOut
      // 判断token是否超时
      if (isTimeOut) {
        store.dispatch('user/logout')
        Message.info('token超时，请重新登陆')
        router.push(`/login?_redirect=${window.location.href.split('#')[1]}`)
        return Promise.reject(new Error('token超时了'))
      }
      config.headers.Authorization = `Bearer ${store.getters.token}`
    }
    return config
  },
  err => {
    return Promise.reject(err)
  }
)

// 响应拦截
instance.interceptors.response.use(
  response => {
    // axios默认加了一层data
    const { success, message, data } = response.data
    if (success) {
      return data
    } else {
      Message.error(message)
      return Promise.reject(new Error(message))
    }
  },
  err => {
    // console.dir(err)
    // 判断返回的状态
    if (err.response && err.response.data && err.response.data.code === 10002) {
      // 登录超时 退出登录
      store.dispatch('user/logout')
      Message.info('登录超时，请重新登陆')
      router.push(`/login?_redirect=${window.location.href.split('#')[1]}`)
    } else {
      Message.error(error.message)
    }

    return Promise.reject(err)
  }
)

export default instance
